#include <stdio.h>
#include <stdlib.h>

#define MAX_PROCESSES 10
#define MAX_QUEUES 5

typedef struct {
    int pid;
    int burstTime;
    int queue;
} Process;

Process processes[MAX_PROCESSES];
int queueLength[MAX_QUEUES] = { 0 };
int queueIndex[MAX_QUEUES] = { 0 };

void addProcess(int pid, int burstTime) {
    processes[pid].pid = pid;
    processes[pid].burstTime = burstTime;
    processes[pid].queue = 0;
    queueLength[0]++;
    queueIndex[0] = 0; // Initialize index for queue 0
}

void runProcess(int pid) {
    printf("Running process %d in queue %d\n", pid, processes[pid].queue);
    processes[pid].burstTime--;
    if (processes[pid].burstTime == 0) {
        printf("Process %d completed\n", pid);
        queueLength[processes[pid].queue]--;
        processes[pid].queue = -1; // Mark as completed
    }
    else {
        processes[pid].queue++;
        if (processes[pid].queue < MAX_QUEUES) {
            queueLength[processes[pid].queue]++;
        }
    }
}

void dispatch() {
    for (int i = 0; i < MAX_QUEUES; i++) {
        while (queueLength[i] > 0) {
            int idx = queueIndex[i]++;
            int pid = idx % MAX_PROCESSES; // Ensure index is within bounds
            if (processes[pid].burstTime > 0 && processes[pid].queue == i) {
                runProcess(pid);
            }
        }
    }
}

void printQueues() {
    for (int i = 0; i < MAX_QUEUES; i++) {
        printf("Queue %d: ", i);
        for (int j = 0; j < queueLength[i]; j++) {
            int idx = (queueIndex[i] + j) % MAX_PROCESSES; // Ensure index is within bounds
            printf("PID %d ", processes[idx].pid);
        }
        printf("\n");
    }
}

int main() {
    // Adding processes to the system
    addProcess(0, 5);
    addProcess(1, 3);
    addProcess(2, 8);
    addProcess(3, 6);

    printf("Initial queue state:\n");
    printQueues();

    // Simulate process dispatch
    while (queueLength[0] > 0 || queueLength[1] > 0 || queueLength[2] > 0 || queueLength[3] > 0 || queueLength[4] > 0) {
        dispatch();
        printf("\nAfter dispatch:\n");
        printQueues();
    }

    return 0;
}